import json
from datetime import datetime
from channels.generic.websocket import WebsocketConsumer
from asgiref.sync import async_to_sync
from django.dispatch import receiver
from .signals import done_signal, work_done
import channels
from .views import create_signal
class ChatConsumer(WebsocketConsumer):
    def connect(self):
        self.room_name = self.scope['url_route']['kwargs']['room_name']
        # self.room_group_name = 'chat_%s' % self.room_name
        self.room_group_name = 'chat'

        # Join room group
        async_to_sync(self.channel_layer.group_add)(
            self.room_group_name,
            self.channel_name
        )

        self.accept()

    def disconnect(self, close_code):
        # Leave room group
        async_to_sync(self.channel_layer.group_discard)(
            self.room_group_name,
            self.channel_name
        )
    # When a user posts a message, a JavaScript function will transmit the message over WebSocket to a ChatConsumer. 
    # The ChatConsumer will receive that message and forward it to the group corresponding to the room name. 
    # Every ChatConsumer in the same group (and thus in the same room) will then receive the message from the group and 
    # forward it over WebSocket back to JavaScript, 
    # where it will be appended to the chat log.
    # Receive message from WebSocket
    def receive(self, text_data, **kwargs):
        text_data_json = json.loads(text_data)
        message = text_data_json['message']
        #The async_to_sync(…) wrapper is required because ChatConsumer is a synchronous WebsocketConsumer 
        # but it is calling an asynchronous channel layer method. (All channel layer methods are asynchronous.)
        # Send message to room group
        print("receive message")
        async_to_sync(self.channel_layer.group_send)(
            self.room_group_name,
            {
                'type': 'chat_message',
                'message': message
            }
        )

    # Receive message from room group
    def chat_message(self, event):
        message = event['message']
        print("send message")
        # Send message to WebSocket
        self.send(text_data=json.dumps({
            'message': message
        }))

# @receiver(work_done, sender="Hello")
def signal_receiver(sender, **kwargs):
    print("我在%s时间收到来自%s的信号，请求url为%s" % (kwargs.get('time'), sender, kwargs.get("path")))
    layer = channels.layers.get_channel_layer()
    async_to_sync(layer.group_send)('chat', {
        'type': 'chat_message',
        'data': {
            'time': kwargs.get('time'),
            'path': kwargs.get('path')
        }
    })
# class ChatConsumer(WebsocketConsumer):
#     def connect(self):
#         print('got connection :'+ str(datetime.now()))
#         self.accept()

#     def disconnect(self, close_code):
#         print('disconnection :'+ str(datetime.now()))
#         pass

#     def receive(self, text_data):
#         text_data_json = json.loads(text_data)
#         message = text_data_json['message']
#         print('receive message :'+ str(datetime.now()))
#         self.send(text_data=json.dumps({
#             'message': "回应消息：" + message
#         }))